﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Jelly2013.Entity;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;

namespace Jelly2013
{
    public class Ticket_Query
    {
        public static string url;
        public static BindingList<TicketInfo> Query(QueryTicketParam queryTicketParam)
        {
            url = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?" +
                "method=queryLeftTicket" +
                "&orderRequest.train_date=" + queryTicketParam.TrainDate +
                "&orderRequest.from_station_telecode=" + queryTicketParam.FormStationTelecode +
                "&orderRequest.to_station_telecode=" + queryTicketParam.ToStationTelecode +
                "&orderRequest.train_no=" + queryTicketParam.TrainNo +
                "&trainPassType=" + queryTicketParam.TrainPassType +
                "&trainClass=" + queryTicketParam.TrainClass +
                "&includeStudent=00" +
                "&seatTypeAndNum=" +
                "&orderRequest.start_time_str=" + queryTicketParam.StartTimeStr;
            string result = CommUitl.getString(url, CommData.cookieContainer, "https://dynamic.12306.cn/otsweb/loginAction.do?method=initForMy12306");
            // 加入日期信息,用于查询多日火车票信息
            result = result.Replace("<span id='id_", queryTicketParam.TrainDate + ",<span id='id_").Trim();
            result = result.Replace("getSelected('", "getSelected('" + queryTicketParam.TrainDate + "#");
            if (result.Contains("系统维护中"))
            {
                throw new Exception("系统维护中!");
            }
            if (result == "-10")
            {
                throw new Exception("您还没有登录或者之前的登录已过期，请点击“登录”/“已登录”按钮。");
            }
            if (result == "-1")
            {
                throw new Exception("服务器忙，加载查询数据失败！");
            }
            return Html2TicketList(result);
        }
        /// <summary>
        /// 根据WEB返回结果生成实体列表
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private static BindingList<TicketInfo> Html2TicketList(string result)
        {
            BindingList<TicketInfo> ticketInfoList = new BindingList<TicketInfo>();
            int numResult;
            if (int.TryParse(result, out numResult) == false)
            {
                Dictionary<string, string> jsInfos = getJsInfo(result);
                #region 取得TrainNo
                result = result.Replace("<span id='id_", string.Empty);
                result = result.Replace("' class='base_txtdiv' onmouseover=javascript:onStopHover('", ",");
                result = result.Replace("') onmouseout='onStopOut()'>", ",");
                #endregion
                result = CommUitl.ReplaceHTMLAttributes(result);
                string[] ticketInfoStrs = result.Split(new string[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries);
                string[] ticketInfos;
                string[] stations;
                TicketInfo ticketInfo;
                for (int i = 0; i < ticketInfoStrs.Length; i++)
                {
                    ticketInfos = ticketInfoStrs[i].Split(',');
                    ticketInfo = new TicketInfo();
                    ticketInfo.TrainDate = ticketInfos[1];
                    ticketInfo.TrainNo = ticketInfos[2];
                    ticketInfo.ID = Convert.ToInt32(ticketInfos[0]);
                    ticketInfo.StationTrainCode = ticketInfos[3 + 1];
                    stations = ticketInfos[3 + 2].Replace("  ", " ").Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    ticketInfo.DepartureStation = stations[0];
                    ticketInfo.DrivingTime = stations[1];
                    stations = ticketInfos[3 + 3].Replace("  ", " ").Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    ticketInfo.DestinationStation = stations[0];
                    ticketInfo.ArrivalTime = stations[1];
                    ticketInfo.ElapsedTime = ticketInfos[3 + 4];
                    //ticketInfo.SeetInfos = new Dictionary<SeatType, string>();
                    //for (int j = 0; j < 11; j++)
                    //{
                    //    ticketInfo.SeetInfos.Add((SeatType)j, ticketInfos[j + 5]);
                    //    //Debug.WriteLine("ticketInfo." + (SeatType)j + "=ticketInfos["+(j + 5)+"];");
                    //}
                    ticketInfo.商务座 = ticketInfos[3 + 5];
                    ticketInfo.特等座 = ticketInfos[3 + 6];
                    ticketInfo.一等座 = ticketInfos[3 + 7];
                    ticketInfo.二等座 = ticketInfos[3 + 8];
                    ticketInfo.高级软卧 = ticketInfos[3 + 9];
                    ticketInfo.软卧 = ticketInfos[3 + 10];
                    ticketInfo.硬卧 = ticketInfos[3 + 11];
                    ticketInfo.软座 = ticketInfos[3 + 12];
                    ticketInfo.硬座 = ticketInfos[3 + 13];
                    ticketInfo.无座 = ticketInfos[3 + 14];
                    ticketInfo.其它 = ticketInfos[3 + 15];
                    try
                    {
                        if (jsInfos.ContainsKey(ticketInfo.TrainDate + ticketInfo.StationTrainCode) == true)
                        {
                            ticketInfo.JsInfoString = jsInfos[ticketInfo.TrainDate + ticketInfo.StationTrainCode];
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    ticketInfoList.Add(ticketInfo);
                }
            }
            return ticketInfoList;
        }
        /// <summary>
        /// 得到预订按钮对应的JS提交信息
        /// </summary>
        /// <param name="webResult"></param>
        /// <returns></returns>
        private static Dictionary<string, string> getJsInfo(string webResult)
        {
            webResult = webResult.Replace("&nbsp;", "");
            string[] tmpRsult;
            Dictionary<string, string> result = new Dictionary<string, string>();
            string jsInfo;
            tmpRsult = webResult.Split(new string[] { "javascript:getSelected('" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < tmpRsult.Length; i++)
            {
                if (tmpRsult[i].Contains("预订"))
                {
                    jsInfo = tmpRsult[i].Split(new string[] { "')>预订" }, StringSplitOptions.RemoveEmptyEntries)[0];
                    result.Add(jsInfo.Split('#')[0] + jsInfo.Split('#')[1], jsInfo);
                }
            }
            return result;
        }
    }
}
